<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsData"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #operation="{ row }">
        <el-button
          link
          type="primary"
          @click="handleEdit(row.id)"
          v-hasPermi="[logisticsSettingsAuthList.declare_rules.edit]"
        >
          编辑
        </el-button>
        <el-button
          link
          type="primary"
          @click="handleDeleteRow(row.id)"
          v-hasPermi="[logisticsSettingsAuthList.declare_rules.delete]"
        >
          删除
        </el-button>
        <el-button
          link
          :type="row.status === 0 ? 'primary' : 'danger'"
          @click="handleStatusRow(row)"
          v-hasPermi="[
            row.status === 0
              ? logisticsSettingsAuthList.declare_rules.enable
              : logisticsSettingsAuthList.declare_rules.disabled,
          ]"
        >
          {{ { 0: "启用", 1: "禁用" }[row.status] }}
        </el-button>
        <el-button
          link
          type="primary"
          @click="handleLog(row)"
          v-hasPermi="[logisticsSettingsAuthList.declare_rules.log]"
        >
          日志
        </el-button>
      </template>
    </VTable>
    <add
      v-model="visibleAdd"
      :id="idAdd"
      @close="idAdd = ''"
      @refresh="refresh"
      :optionsData="optionsData"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="base.declare-rules"
      :business_id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
import { overallOptions } from "@/api/public";
import { strHump } from "@/utils/index";
import add from "./add/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import {
  statusDeclareRules,
  deleteDeclareRules,
  declareRulesList,
} from "./api";
import Log from "@/components/Log/index.vue";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
const router = useRouter();

const { proxy } = getCurrentInstance();
const tableRef = ref();

const optionsData = ref({});
const tableOptins = reactive({
  formConfig: {
    data: {
      rule_name: "",
      status: "",
      create_user: "",
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", type: "seq" },
    {
      fixed: "left",
      title: "规则名称",
      minWidth: 200,
      field: "rule_name",
    },
    {
      title: "重量计算方式",
      minWidth: 200,
      slots: {
        default: ({ row }) => {
          return row.polymers.map((n) => (
            <div key={n.weight_calc}>{n.weight_calc}</div>
          ));
        },
      },
    },
    {
      title: "价格计算方式",
      minWidth: 200,
      slots: {
        default: ({ row }) => {
          return row.polymers.map((n) => (
            <div key={n.price_calc}>{n.price_calc}</div>
          ));
        },
      },
    },
    {
      title: "状态",
      width: 90,
      field: "status",
      slots: {
        default: ({ row }) => {
          return <VstatusRender code={row} />;
        },
      },
    },
    { title: "创建人", width: 170, field: "create_user" },
    { title: "创建时间", width: 170, field: "create_time" },
    { title: "更新时间", width: 170, field: "update_time" },
    {
      title: "操作",
      width: 200,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return declareRulesList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "rule_name",
    type: "input",
    placeholder: "规则名称",
    ...publicStyle,
  },
  {
    field: "status",
    placeholder: "状态",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
    style: { width: "90px" },
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
  {
    field: "create_user",
    slot: "create_user",
  },
];

onMounted(() => {
  getOption();
});

const getOption = async () => {
  const option = "base.declare-rules";
  const _country = "map.country";
  const { data } = await overallOptions({
    params: [option, _country],
  });
  const _hump = strHump(option);
  if (data[_hump]) {
    optionsData.value = data[_hump];
  }
  if (data[strHump(_country)]) {
    optionsData.value[strHump(_country)] = data[strHump(_country)];
  }
};

const handleStatus = (status) => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  handleStatusReq(rows, status);
};
const handleStatusRow = (row) => {
  handleStatusReq([row.id], row.status ? 0 : 1);
};
const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{flag ? "启用" : "禁用"}选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await statusDeclareRules({ id, status: flag ? 1 : 0 });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleDelete = () => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  handleDeleteReq(rows);
};
const handleDeleteRow = (id) => {
  handleDeleteReq(id);
};
const handleDeleteReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deleteDeclareRules({ id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const idAdd = ref();
const visibleAdd = ref(false);
const handleEdit = (_id) => {
  idAdd.value = _id;
  visibleAdd.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["logistics_rules_manage"],
    condition,
  });
};

const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: () => (visibleAdd.value = true),
    permission: [logisticsSettingsAuthList.declare_rules.add],
  },
  {
    label: "启用",
    icon: "state_finish_line_1",
    type: "primary",
    fn: () => handleStatus(true),
    permission: [logisticsSettingsAuthList.declare_rules.enable],
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
    permission: [logisticsSettingsAuthList.declare_rules.disabled],
  },
    {
    label: "删除",
    icon: "del",
    fn: handleDelete,
    permission: [logisticsSettingsAuthList.declare_rules.delete],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsSettingsAuthList.declare_rules.export],
  },
];
</script>
